<template>
  <div>
      <div class="card-item section" v-for="(card,index) in contacts_cards" :key="index">
        <FormItem
          :required="level_type == 2"
          label="证件类型">
          <select v-model="card.type" @change='changeCardType(index)'>
            <option v-for="type in contactCardTypesNoSelected(card.type)" :key="type.value" :value="type.value">{{type.label}}</option>
          </select>
        </FormItem>

        <!-- 通过现有会员证明 -->
        <template v-if="card.type == 4">
          <template v-for="(prover,idx) in card.provers">
            <FormItem
              :required="level_type == 2"
              :key="idx + 'name'"
              :label="'会员'+(idx+1)+'全名/昵称（单位名称或单位简称）'">
              <Input v-model="prover.name" :placeholder="'请输入会员'+(idx+1)+'全名/昵称（单位名称或单位简称）'"/>
            </FormItem>
            <FormItem
              :required="level_type == 2"
              :key="idx + 'code'"
              :label="'会员户口号'+(idx+1)">
              <Input v-model="prover.code" filter="int" :placeholder="'请输入会员户口号'+(idx+1)"/>
            </FormItem>
          </template>
        </template>
        <template v-else>
          <template v-if="card.type == 3">
            <FormItem
              :required="level_type == 2"
              label="证件名称">
              <Input v-model="card.name" placeholder="请输入其他证件名称，如驾驶证，军人证等"/>
            </FormItem>
          </template>
          <FormItem
            :required="level_type == 2"
            label="证件号码">
            <Input v-model="card.code" placeholder="请输入对应的证件号码"/>
          </FormItem>

          <FormItem
            :required="level_type == 2"
            label="证件照片"
            subtip="上传证件照片，jpg，jpeg，png格式的图片，如果是身份证需要上传正反面（单个不超过5M）">
            <div class="upload-group">
              <UploadItem
                :params=[index,pidx]
                @change="fileChange($event,pic)"
                v-for="(pic,pidx) in card.pics"
                :value="pic.url"
                :progress="pic.progress"
                :thumb="pic.thumb"
                :key="pidx" :label="card.type != 2 ? '上传证件照' : (pidx == 0 ? '上传身份证正面照' : '上传身份证反面照') "/>
            </div>
          </FormItem>
        </template>
        <button class="btn btn-danger btn-block btn-outline" v-if="contacts_cards.length >1" @click="delCard(index)">删除此证件</button>
      </div>

      <div class="section" v-show="this.contactCardTypesNoSelected().length">
        <button class="btn btn-primary btn-block btn-outline" @click="addCard">+添加其他证件</button>
      </div>
    <div class="page-footer">
      <button class="btn btn-primary btn-block" :disabled="!formValid" @click="submit">下一步</button>
    </div>
  </div>
</template>
<script>
import Input from '~/components/Input';
import Radio from '~/components/Radio'
import Checkbox from '~/components/Checkbox'
import FormItem from '~/components/CompleteItem'
import Modal from '~/components/Modal';
import UploadItem from '~/components/UploadItem'

export default {
  components:{
    Input,
    Radio,
    FormItem,
    Checkbox,
    Modal,
    UploadItem
  },
  data(){
    return {
      contacts_cards:[],
      uploader:'',
      step:6,
      showPopup:false,
      pageData:{},
      level_type: 1,
    }
  },
  computed:{
    formValid(){
      let flag = !!this.contacts_cards.length;
      if(flag){
        for(let i=0,len = this.contacts_cards.length;i<len;i++){
          let item = this.contacts_cards[i];
          if(item.type == 4){ // 证明人
            flag = this.level_type != 2 ||
                  ( String(item.provers[0].name).trim()
                    && String(item.provers[0].code).trim()
                    && String(item.provers[1].name).trim()
                    && String(item.provers[1].code).trim()
                  )
          }else if(item.type == 2){ // 身份证
            flag = this.level_type != 2 ||
                  ( String(item.code).trim()
                    && String(item.pics[0].name).trim()
                    && String(item.pics[0].url).trim()
                    // && String(item.pics[1].name).trim()
                    // && String(item.pics[1].url).trim()
                  )
          }else {
            flag = this.level_type != 2 ||
                  ( String(item.code).trim()
                    && String(item.pics[0].name).trim()
                    && String(item.pics[0].url).trim()
                  )
            if(item.type == 3){
              flag = flag && (this.level_type != 2 ||
                ( String(item.name).trim()
                    && String(item.code).trim()
                    && String(item.pics[0].name).trim()
                    && String(item.pics[0].url).trim()
                  )
              )
            }
          }

          if(!flag) break;
        }
      }
      return flag;
    },
    contactCardTypesNoSelected(){
      return (type)=>{
        var rs = [];
        for(let key in this.pageData.contact_card_types){
          if(type == key || !this.contacts_cards.find(item=>item.type == key)){
            rs.push({
              value:key,
              label:this.pageData.contact_card_types[key]
            })
          }
        }
        return rs;
      }
    }
  },
  async mounted(){
    this.$emit('setTitle','证件信息');

    await this.getCompleteInfo();

    this.$store.commit('completeInfo/setStep',this.$route.name);

    //上传
    this.initUpload();

    if(this.$tools.isLema && this.$tools.isAndroid){//index,subindex,url,name,token
      window.insertImg = (index,subindex,url,name,token)=>{
        this.$set(this.contacts_cards[index].pics,subindex,{
          name,
          url
        })
        if(token){
          this.$store.commit('SET_TOKEN',token);
        }
      }
    }
  },
  methods:{
    initUpload(){
      this.uploader = WebUploader.create({
        // 选完文件后，是否自动上传。
        auto: true,
        // 文件接收服务端。
        server: window.BASE_URL + "?ct=api&ac=upload&os=web",
        // 只允许选择图片文件。
        accept: {
          title: "Images",
          extensions: "gif,jpg,jpeg,bmp,png",
          mimeTypes: "image/*",
        },
        chunked: true,
        chunkSize: 1 * 1024 * 1024,
        // formData: {
        //   'formname': 'tmp', // 上传表单名称
        //   'randname': true, // 是否随机生成文件名
        //   'dir': 'tmp', // 上传文件目录
        //   'thumb_w': 0,
        //   'thumb_h': 0,
        // },
        fileNumLimit:1,
      });

      this.uploader.on("uploadBeforeSend", (object, data, headers) => {
        // headers["X-Requested-With"] = "XMLHttpRequest"
        // data.guid = object.file.guid;
        data.post_data = JSON.stringify({
          "uid":this.$store.state.uid,
          "token":this.$store.state.token,
          "guid":object.file.guid,
          'formname': 'file', // 上传表单名称
        })
      });

      // 上传成功
      this.uploader.on("uploadSuccess", (file, response) => {
        let res = JSON.parse(response._raw);
        //成功之后根据guid找多对应的pic
        for(let i = 0,len = this.contacts_cards.length;i<len;i++){
          let item = this.contacts_cards[i];
          let isBreak  = false;

          if(item.pics){
            for(let p = 0,plen = item.pics.length;p<plen;p++){
              let pic = item.pics[p];
              if(pic.guid === file.guid){
                pic.url = res.data.filelink;
                pic.name = res.data.filename;
                pic.progress = false;
                pic.error = false;
                isBreak = true;
                break;
              }
            }
          }
          if(isBreak) break;
        }

      });

      // 上传失败
      this.uploader.on("uploadError", (file, reason) => {
        this.$toast('上传出错');
        //成功之后根据guid找多对应的pic
        for(let i = 0,len = this.contacts_cards.length;i<len;i++){
          let item = this.contacts_cards[i];
          let isBreak  = false;
          if(item.pics){
            for(let p = 0,plen = item.pics.length;p<plen;p++){
              let pic = item.pics[p];
              if(pic.guid === file.guid){
                pic.progress = false;
                pic.error = true;
                pic.thumb = '';
                isBreak = true;
                break;
              }
            }
          }
          if(isBreak) break;
        }
      });


      // 图片不能大于2M
      this.uploader.on("beforeFileQueued", file => {
          if (file.size > 5 * 1024 * 1024) {
              this.$toast("图片不能超过5M");
              return false;
          }

          file.guid = WebUploader.Base.guid();
      });
    },
    async getCompleteInfo(){
      this.$emit('loading',true);
      try{
        let {data:rs} = await this.$axios.post('?ct=api&ac=get_complete_info',{
          step:this.step,
        })
        if(rs.code == 0){
          this.pageData = rs.data;
          this.level_type = this.pageData.page_data.level_type;
          let {page_data} = rs.data;

           //初始化数据
          if(!page_data.contacts_cards.length){
            //如果上一步选择加密，证件信息为空的话，默认选择证明人
            this.addCard(page_data.is_secret);
          }else{

            //补充图片对象
            // 身份证限制两个图片
            // 其他证件限制一个
            page_data.contacts_cards.forEach(item=>{
              if(item.type != 4){
                if(item.type == 2){
                    for(let i = 0,len = 2- item.pics.length;i<len;i++){
                      item.pics.push({
                        name:'',
                        url:''
                      })
                    }
                }else{
                  if(!item.pics.length){
                    item.pics.push({
                      name:'',
                      url:''
                    })
                  }
                }
              }
            })
             this.contacts_cards = page_data.contacts_cards;
          }
        }else{
          this.$toast(rs.msg);
        }
      }catch(e){
        this.$error(e);
      }
      this.$emit('loading',false);

    },
    addFile(file,pic){
      // 为pic添加一个guid，上传成功后根据pic的guid索引修改图片的值
      this.uploader.reset();
      this.uploader.addFiles(file);
      let fs = this.uploader.getFiles();
      if(fs && fs[0]){
        pic.guid = fs[0].guid;
        this.uploader.upload();
        this.uploader.makeThumb(fs[0],(error,ret)=>{
          if(error){
            this.$alert('生成预览图失败');
          }else{
            this.$set(pic,'progress',true);
            this.$set(pic,'thumb',ret);
          }
        })
      }
    },
    fileChange(file,pic){
      this.addFile(file.files[0],pic)
    },
    delCard(idx){
      this.contacts_cards.splice(idx,1);
    },
    addCard(isSecret){
      if(this.contactCardTypesNoSelected().length == 0){
        this.$toast('没有更多选项');
        return false;
      }
      let type = isSecret == 1 ? '4' : this.contactCardTypesNoSelected()[0].value;
      let item = this.getAddTypeItem(type);
      this.contacts_cards.push(item)
    },
    changeCardType(index){ // 修改选项卡时要修改对应的item
      let item = this.contacts_cards[index];
      let rs = this.getAddTypeItem(item.type);

      this.$set(this.contacts_cards,index,rs)
    },
    getAddTypeItem(type){ // 根据type 返回对应的item
      let item = {};
      switch(type){
        case '4':
          item = {
            type:type,
            name:'',
            provers:[{
                name:'',
                code:'',
            },{
                name:'',
                code:''
            }]
          }
          break;
        case '2':
          item = {
            type:type,
            code:'',
            name:'',
            pics:[{
              name:'',
              code:''
            },{
              name:'',
              code:''
            }]
          }
          break;
        default:
          item = {
            type:type,
            code:'',
            name:'',
            pics:[{
              name:'',
              code:''
            }]
          }
          break;
      }

      return item;
    },
    submit(){
      if(this.loading) return false;
      if(!this.formValid){
        this.$toast('请完善表单信息');
        return false;
      }
      let contacts_cards = [];
       this.contacts_cards.forEach(item=>{
         if(item.pics){
           let tmp = {
             type:item.type,
             name:item.name,
             code:item.code,
             pics:[]
           }
          item.pics.forEach(pic=>{
            tmp.pics.push({
              name:pic.name,
              url:pic.url
            })
          })
          contacts_cards.push(tmp);
         }else{
           contacts_cards.push(item);
         }
       });
      this.$emit('submit',{
        step:this.step,
        contacts_cards,
      },()=>{

        this.$emit('setTitle', '个人对接人信息');
        this.$router.push({name:'complete_info-dock_people'})
      })

    },
  }
}
</script>
<style lang="less" scoped>
.page-top-tip {
  margin-bottom:40px;
  font-size:24px;
  color:#c0c3cc;
  code {
    color:#f05521;
    font-style: normal;
  }
}

.section + .section {
  border-top: 14px solid #edeef0;
}
</style>

